import { listUserByPageUsingPost } from '@/services/backend/userController';
import { UserOutlined, TrophyOutlined, StarOutlined, TeamOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { Avatar, Card, Col, Rate, Row, Spin, Typography, Tag, Divider, Badge } from 'antd';
import React, { useEffect, useState } from 'react';
import './style.less';

const { Title, Paragraph } = Typography;
const { Meta } = Card;

// 扩展教练数据类型
type EnhancedCoach = API.UserVO & {
  description?: string;
  rating?: number;
  specialties?: string[];
  experience?: number;
  certificates?: string[];
};

// 教练专长领域数据
const specialtiesOptions = [
  '青少年培训', '技术训练', '战术分析', '体能训练',
  '守门员训练', '进攻训练', '防守训练', '心理辅导'
];

// 教练证书数据
const certificatesOptions = [
  'AFC A级教练员证书', 'AFC B级教练员证书', 'AFC C级教练员证书',
  'CFA D级教练员证书', '国家一级裁判证', '体育教育学学士'
];

const ExcellentCoaches: React.FC = () => {
  const [loading, setLoading] = useState<boolean>(true);
  const [coaches, setCoaches] = useState<EnhancedCoach[]>([]);

  const fetchExcellentCoaches = async () => {
    try {
      setLoading(true);
      const res = await listUserByPageUsingPost({
        role: 'coach',
        pageSize: 8,
        current: 1,
        sortField: 'create_time',
        sortOrder: 'desc',
      });

      if (res.code === 0 && res.data) {
        // 模拟为教练添加评分和描述（实际项目中应从后端获取）
        const coachesWithDetails = res.data.records.map((coach) => {
          // 随机生成专长领域
          const specialties = [...specialtiesOptions]
            .sort(() => 0.5 - Math.random())
            .slice(0, Math.floor(Math.random() * 3) + 2);

          // 随机生成证书
          const certificates = [...certificatesOptions]
            .sort(() => 0.5 - Math.random())
            .slice(0, Math.floor(Math.random() * 2) + 1);

          // 随机生成教练经验年限
          const experience = Math.floor(Math.random() * 15) + 5;

          return {
            ...coach,
            rating: 4 + Math.random(),
            experience,
            specialties,
            certificates,
            description: `${coach.username || '教练'} 是一位经验丰富的足球教练，拥有${experience}年执教经验，专注于${specialties.join('、')}。曾带领多支球队获得优异成绩，善于发掘和培养年轻球员的潜力，注重培养球员的团队合作精神和个人技术能力。`,
          };
        });

        // 按评分排序
        coachesWithDetails.sort((a, b) => (b.rating || 0) - (a.rating || 0));
        setCoaches(coachesWithDetails);
      }
    } catch (error) {
      console.error('获取优秀教练数据失败', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchExcellentCoaches();
  }, []);

  // 根据评分获取对应的标签颜色
  const getRatingColor = (rating?: number) => {
    if (!rating) return 'blue';
    if (rating >= 4.8) return 'red';
    if (rating >= 4.5) return 'orange';
    return 'blue';
  };

  return (
    <PageContainer
      header={{
        title: '优秀教练团队',
        subTitle: '我们拥有一支专业的教练团队，为学员提供高质量的足球训练',
        ghost: true,
      }}
      className="excellent-coaches-container"
    >
      <div className="page-header">
        <Title level={2} className="page-title">
          <TeamOutlined className="title-icon" />
          专业教练团队
        </Title>
        <Paragraph className="page-description">
          我们的教练团队由经验丰富的专业人士组成，他们不仅拥有丰富的足球知识和执教经验，
          还具备出色的沟通能力和教学方法。每位教练都致力于帮助学员发掘潜力，提升技能，
          培养团队精神和体育道德。
        </Paragraph>
      </div>

      <Spin spinning={loading}>
        <Row gutter={[24, 24]} style={{ marginTop: 24 }}>
          {coaches.map((coach, index) => (
            <Col xs={24} sm={12} md={8} lg={6} key={coach.id || index}>
              <Badge.Ribbon
                text={index < 3 ? `TOP ${index + 1} 教练` : ''}
                color={index === 0 ? 'red' : index === 1 ? 'orange' : 'green'}
                style={{ display: index < 3 ? 'block' : 'none' }}
              >
                <Card
                  hoverable
                  className="coach-card"
                  cover={
                    <div className="coach-avatar-container" style={{
                      background: index < 3
                        ? `linear-gradient(135deg, #f5f5f5 0%, #e0e0e0 100%)`
                        : '#f5f5f5',
                    }}>
                      {index < 3 && (
                        <TrophyOutlined className="trophy-icon" />
                      )}
                      <Avatar
                        size={120}
                        src={coach.avatar}
                        icon={<UserOutlined />}
                        className="coach-avatar"
                      />
                      <div className="coach-basic-info">
                        <Title level={4} className="coach-name">
                          {coach.username || '未知教练'}
                        </Title>
                        <div className="coach-rating">
                          <Rate disabled defaultValue={coach.rating} allowHalf />
                          <span className="rating-text">
                            {coach.rating?.toFixed(1) || '0.0'}
                          </span>
                        </div>
                        <Tag color={getRatingColor(coach.rating)} className="experience-tag">
                          {coach.experience}年教龄
                        </Tag>
                      </div>
                    </div>
                  }
                >
                  <div className="coach-details">
                    <Paragraph
                      ellipsis={{
                        rows: 3,
                        expandable: true,
                        symbol: '更多',
                      }}
                      className="coach-description"
                    >
                      {coach.description}
                    </Paragraph>

                    <Divider className="section-divider" />

                    <div className="coach-specialties">
                      <Title level={5} className="section-title">
                        <StarOutlined className="section-icon" />
                        专长领域
                      </Title>
                      <div className="tags-container">
                        {coach.specialties?.map((specialty) => (
                          <Tag color="blue" key={specialty} className="specialty-tag">
                            {specialty}
                          </Tag>
                        ))}
                      </div>
                    </div>

                    <div className="coach-certificates">
                      <Title level={5} className="section-title">
                        <TrophyOutlined className="section-icon" />
                        资质证书
                      </Title>
                      <div className="tags-container">
                        {coach.certificates?.map((certificate) => (
                          <Tag color="green" key={certificate} className="certificate-tag">
                            {certificate}
                          </Tag>
                        ))}
                      </div>
                    </div>
                  </div>
                </Card>
              </Badge.Ribbon>
            </Col>
          ))}
        </Row>
      </Spin>
    </PageContainer>
  );
};

export default ExcellentCoaches;
